package com.zhenglvhang.controller;

import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.zhenglvhang.util.ResUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@RestController
public class UploadController {

//    @Value("wx.store.path")
//    private String wxStorePath;

    @GetMapping("/upload/store/path/show")
    public Object getWxStorePath() {
        String wxStorePath = ResUtil.getProperty("wx.store.path");
        return wxStorePath;
    }

    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile srcFile) {
        String wxStorePath = ResUtil.getProperty("wx.store.path");
        HashMap<String, String> map = Maps.newHashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String subDirectory = sdf.format(new Date());
        File directoryToday = new File(wxStorePath, subDirectory);
        String originalFilename = srcFile.getOriginalFilename();
        String fileExtension = Files.getFileExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        File destFile = new File(directoryToday, String.format(uuid, fileExtension));

        try {
            byte[] bytes = srcFile.getBytes();
            Files.write(bytes, destFile);

            map.put("success", "true");
            map.put("msg", "上传成功!");
            map.put("file", destFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();

            map.put("success", "false");
            map.put("msg", "上传失败!");
        }

        return map;
    }
}
